package com.bsj.power.pls.config.cached;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author yinhao
 * @version 1.0
 * @description 计数器
 * @date 2024/10/16
 */
@Slf4j
public class OrderCounter {

    static class OrderNumber{
        //最大序列号
        private static final int MAX_VALUE = 254;
        //初始化为1
        private final AtomicInteger orderNumberCounter = new AtomicInteger(1);

        public OrderNumber(){}

        public int generateOrderNumber() {
            int currentValue = orderNumberCounter.getAndIncrement();
            if (currentValue > MAX_VALUE) {
                orderNumberCounter.set(1); // 重置计数器
                currentValue = orderNumberCounter.getAndIncrement();
            }
            return currentValue;
        }
    }

    private static Map<String, OrderNumber> orderNumberMap = new ConcurrentHashMap<>();

    private static ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();

    /**
     * 取包序号
     * @return
     */
    public static int getNum() {
        rwlock.readLock().lock();
        try {
            String id = "RTK-NUM";
            OrderNumber orderNumber = orderNumberMap.get(id);
            if (orderNumber == null) {
                orderNumber = new OrderNumber();
                orderNumberMap.put(id, orderNumber);
            }
            return orderNumber.generateOrderNumber();
        } finally {
            rwlock.readLock().unlock();
        }
    }
}
